package club.qweqwe.filter;

import club.qweqwe.exception.BaseException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

public class BaseFilter extends HttpFilter {
    private String errorPage;
    @Override
    public void init() throws ServletException {
        errorPage = getServletContext().getInitParameter("ErrorPage");
    }

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            doFilterEx(request, response, chain);
        }catch (BaseException e){
            response.setContentType("application/json");
            response.getWriter().print(e.toJsonString());
        } catch (IllegalAccessException | InvocationTargetException e) {

            if(errorPage != null)
                request.getRequestDispatcher("/" + errorPage).forward(request, response);
            e.printStackTrace();
        }
    }

    protected void doFilterEx(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException, IllegalAccessException, InvocationTargetException {
    }
}
